﻿using System.Linq;
using System.Windows.Controls;

// ReSharper disable once CheckNamespace
namespace IFoxCAD.WPF;

public class GridHelper
{
    #region Rows

    public static void SetRows(DependencyObject obj, string value)
    {
        obj.SetValue(RowsProperty, value);
    }

    public static readonly DependencyProperty RowsProperty =
        DependencyProperty.RegisterAttached("Rows", typeof(string), typeof(GridHelper),
            new PropertyMetadata(string.Empty, OnRowsChanged));

    private static void OnRowsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is not Grid grid)
            return;
        grid.RowDefinitions.Clear();
        var rows = ((string)e.NewValue).Split(',').Select(x => x.Trim());
        foreach (var row in rows)
        {
            grid.RowDefinitions.Add(new RowDefinition { Height = ParseGridLength(row) });
        }
    }

    #endregion

    #region Columns

    public static void SetColumns(DependencyObject obj, string value)
    {
        obj.SetValue(ColumnsProperty, value);
    }

    public static readonly DependencyProperty ColumnsProperty =
        DependencyProperty.RegisterAttached("Columns", typeof(string), typeof(GridHelper),
            new PropertyMetadata(string.Empty, OnColumnsChanged));

    private static void OnColumnsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is not Grid grid)
            return;
        grid.ColumnDefinitions.Clear();
        var columns = ((string)e.NewValue).Split(',').Select(x => x.Trim());
        foreach (var column in columns)
        {
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = ParseGridLength(column) });
        }
    }

    #endregion

    private static GridLength ParseGridLength(string length)
    {
        if (length.EndsWith("*"))
        {
            double starNum = 1;
            if (length.Length > 1)
                starNum = double.Parse(length.Substring(0, length.Length - 1));
            return new GridLength(starNum, GridUnitType.Star);
        }

        if (length.Equals("auto", StringComparison.OrdinalIgnoreCase))
        {
            return GridLength.Auto;
        }

        if (double.TryParse(length, out var value))
        {
            return new GridLength(value);
        }

        throw new ArgumentException("Invalid GridLength value: " + length);
    }
}